package com.mall.controller;

import com.alibaba.fastjson.JSONObject;
import com.mall.entity.Address;
import com.mall.entity.User;
import com.mall.exception.DeleteException;
import com.mall.exception.InsertException;
import com.mall.service.AddressService;
import com.mall.utils.UserCache;
import com.mall.vo.WebResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/address")
public class AddressController {

    @Autowired
    private AddressService addressService;

    @PostMapping("/add")
    public WebResult<JSONObject> addAddress(@RequestBody Address address) throws InsertException {
        Integer addressId = addressService.addAddress(address);
        JSONObject res = new JSONObject();
        res.put("addressId",addressId);
        return WebResult.<JSONObject>builder()
                .code(10000)
                .data(res)
                .message(WebResult.REQUEST_STATUS_SUCCESS)
                .build();
    }

    @GetMapping("/getByUserId")
    public WebResult<JSONObject> getByUserId() {
        User user = UserCache.get();
        List<Address> addressList = addressService.getByUserId(user.getId());
        JSONObject res = new JSONObject();
        res.put("addressList",addressList);
        return WebResult.<JSONObject>builder()
                .code(10000)
                .message(WebResult.REQUEST_STATUS_SUCCESS)
                .data(res)
                .build();
    }

    @DeleteMapping("/delete")
    public WebResult<String> deleteAddress(@RequestParam Integer id) throws DeleteException {
        addressService.deleteById(id);
        return WebResult.<String>builder()
                .code(10000)
                .message("删除成功")
                .build();
    }

}